﻿
function sendAjax(param) {

}

//模块：
reds3d.widget.bindClass(reds3d.widget.BaseWidget.extend({
  options: {
    //弹窗
    view: {
      type: "window",
      url: "view.html",
      windowOptions: {
        width: 250,
        position: {
          "top": 55,
          "right": 5,
          "bottom": 5
        }
      }
    },
  },
  drawControl: null,
  selectEntity:[],
  //初始化[仅执行1次]
  create: function () {
    var that = this;
    this.drawControl = new reds3d.Draw({
      viewer: this.viewer,
      hasEdit: false,
      dragIcon: 'img/dragIcon.png',
      tooltip: true,
      onStopDrawing: function (entity) {
        if (that.viewWindow)
          that.viewWindow.plotlist.plotEnd();
        that.saveEntity(entity);
      },
      onStartEditing: function (entity) {
        that.startEditing(entity);
      },
      onChangeEditing: function (entity) {
        that.startEditing(entity);
      },
      onStopEditing: function (entity) {
        that.stopEditing(entity);
        if (entity != null)
          that.saveEntity(entity);
      },
    });

    //添加到图层控制
    bindToLayerControl({
      pid: 0,
      name: '标绘',
      visible: true,
      onAdd: function () { //显示回调
        that.drawControl.setVisible(true);
      },
      onRemove: function () { //隐藏回调
        that.drawControl.setVisible(false);
      },
      onCenterAt: function (duration) { //定位回调
        var arr = that.drawControl.getEntitys();
        that.viewer.flyTo(arr, {
          duration: duration
        });
      },
    });

    window.addEventListener('message', e => {
      console.log('子页面接受到上图消息', e);
      if (e.data.type !== 'draw') return;
      const data = e.data.data;
      this.drawControl.jsonToEntity(data, true, true);
    })

    // this.getList();
  },
  viewWindow: null,
  //每个窗口创建完成后调用
  winCreateOK: function (opt, result) {
    this.viewWindow = result;
  },
  //激活插件
  activate: function () {
    this.datasource = new Redslib.CustomDataSource("svgLayer");
    this.viewer.dataSources.add(this.datasource);
    this.drawControl.hasEdit(true);
  },
  //释放插件
  disable: function () {
    this.viewWindow = null;
    this.drawControl.hasEdit(false);
    //this.deleteAll();

    var storagedata = JSON.stringify(this.getGeoJson());
    haoutil.storage.add(this.storageName, storagedata);
  },

  //开始标记
  startDraw: function (defval) {
    //console.log(JSON.stringify('开始标记'+defval));
    this.drawControl.startDraw(defval);
  },
  startEditingById: function (id) {
    var entity = this.drawControl.getEntityById(id);
    if (entity == null) return;

    this.viewer.flyTo(entity);

    entity.startEditing();
  },
  startEditing: function (entity) {
    var lonlats = this.drawControl.getCoordinates(entity);
    this.viewWindow.plotEdit.startEditing(entity.attribute, lonlats);
    this.selectEntity=lonlats;
  },
  stopEditing: function (layer) {
    if (this.viewWindow)
      this.viewWindow.plotEdit.stopEditing();
  },
  //更新图上的属性
  updateAttr2map: function (attr) {
    if (attr.name == "矢量标记") {
      this.datasource.entities.removeAll();
      if (attr.style.svgStr == null) {
        attr.style.svgStr = this.readFile(attr.style.image);
        console.log(attr.style.svgStr);
      }
      //宽
      if (attr.style.width != 250) {
        var reg = new RegExp('width="250"', "g");
        attr.style.svgStr = attr.style.svgStr.replace(reg, 'width="' + attr.style.width + '"');
      }
      //高
      if (attr.style.height != 220) {
        var reg = new RegExp('height="220"', "g");
        attr.style.svgStr = attr.style.svgStr.replace(reg, 'height="' + attr.style.height + '"');
      }
      //填充颜色
      if (attr.style.fill != "#bf5f00") {
        var reg = new RegExp('fill="#bf5f00"', "g");
        attr.style.svgStr = attr.style.svgStr.replace(reg, 'fill=' + attr.style.fill);
      }
      //边框颜色
      if (attr.style.stroke != "#000000") {
        var reg = new RegExp('stroke=""#000000""', "g");
        attr.style.svgStr = attr.style.svgStr.replace(reg, 'stroke="' + attr.style.stroke + '"');
      }
      //边框宽度
      if (attr.style.strokeWidth != 1) {
        var reg = new RegExp('stroke-width="1"', "g");
        attr.style.svgStr = attr.style.svgStr.replace(reg, 'stroke-width="' + attr.style.strokeWidth + '"');
      }
      this.createRectangle(attr.style.svgStr,{
        //坐标
        longitude: this.selectEntity[0][0],
        latitude: this.selectEntity[0][1],
    });
    }
    this.drawControl.updateAttribute(attr);
  },
  //更新图上的几何形状、坐标等
  updateGeo2map: function (coords, withHeight) {
    var positions = coords;
    if (positions.length == 2) {
      positions = Redslib.Cartesian3.fromDegrees(Number(coords[0]).toFixed(6), Number(coords[1]).toFixed(6), Number(0));
    } else if (positions.length == 3) {
      positions = Redslib.Cartesian3.fromDegrees(Number(coords[0]).toFixed(6), Number(coords[1]).toFixed(6), Number(coords[2]).toFixed(2));
    } else if (positions.length > 3) {
      if (withHeight) {
        positions = Redslib.Cartesian3.fromDegreesArrayHeights(coords);
      } else {
        positions = Redslib.Cartesian3.fromDegreesArray(coords);
      }
    }
    this.drawControl.updateGeometry(positions);

    if (positions.length <= 3) {
      this.centerCurrentEntity();
    }

    return positions;
  },
  centerCurrentEntity: function () {
    var entity = this.drawControl.getCurrentEntity();
    if (entity == null) return;
    this.viewer.flyTo(entity);
  },
  //文件处理
  getGeoJson: function () {
    return this.drawControl.toGeoJSON();
  },
  jsonToLayer: function (json, isClear, isFly) {
    if (json == null) return;
    return this.drawControl.jsonToEntity(json, isClear, isFly);
  },
  deleteAll: function () {
    this.drawControl.deleteAll();
  },
  deleteEntity: function (id) {
    var entity = this.drawControl.getEntityById(id);
    if (entity == null) return;

    this.drawControl.deleteEntity(entity);
  },
  deleteCurrentEntity: function () {
    var entity = this.drawControl.getCurrentEntity();
    if (entity == null) return;

    this.drawControl.deleteCurrentEntity();
  },
  hasEdit: function (val) {
    this.drawControl.hasEdit(val);
  },
  //搜索
  query: function (text, maxcount) {
    var arrEntity = this.drawControl.getEntitys();

    var arr = [];
    var counts = 0;
    for (var i = 0; i < arrEntity.length; i++) {
      var entity = arrEntity[i];

      var name;
      if (entity.attribute.type === "label") {
        name = entity.attribute.style.text;
      } else if (entity.attribute.attr) {
        name = entity.attribute.attr.name;
      }

      if (name == null || name.indexOf(text) == -1) continue;

      arr.push({
        name: name,
        type: '标绘 - ' + entity.attribute.name,
        _datatype: 'plot',
        _entity: entity
      });

      if (maxcount) {
        counts++;
        if (counts > maxcount) break;
      }
    }
    return arr;
  },
  //弹窗属性编辑处理
  last_window_param: null,
  showEditAttrWindow: function (param) {
    this.last_window_param = param;

    //layer.open({
    //    type: 2,
    //    title: '选择数据',
    //    fix: true,
    //    shadeClose: false,
    //    maxmin: true,
    //    area: ["100%", "100%"],
    //    content: "test.html?name=" + param.attrName + "&value=" + param.attrVal,
    //    skin: "layer-wing-dialog animation-scale-up",
    //    success: function (layero) {

    //    }
    //});
  },
  saveWindowEdit: function (attrVal) {
    this.viewWindow.plotEdit.updateAttr(this.last_window_param.parname, this.last_window_param.attrName, attrVal);
    layer.close(layer.index);
  },
  storageName: "winggis_plot",
  getList: function () {
    var that = this;

    var laststorage = haoutil.storage.get(this.storageName); //读取localStorage值
    if (laststorage == null || laststorage == 'null') {
      $.getJSON("../data/geojson/plot.json", function (result) {
        if (!that.isActivate) return;
        that.jsonToLayer(result, true, true);
      });
    } else {
      that.jsonToLayer(JSON.parse(laststorage), true, true);
    }

  },
  saveEntity: function (entity) {
    entity._attribute.attr = entity._attribute.attr || {};
    entity._attribute.attr.id = (new Date()).format("yyyyMMddHHmmss");
    //方海平20210330修改，对entity的属性值进行判断，避免position导致的错误。需要注意对圆类型需要特殊处理
    if (entity._attribute.position != undefined) {
      if (!entity._attribute.position.hasOwnProperty('height')) {
        var json = this.drawControl.toGeoJSON(entity);
        sendAjax({
          url: '',
          data: {
            id: json.properties.attr.id,
            name: json.properties.attr.name,
            remark: json.properties.attr.remark,
            type: json.properties.type,
            coordinates: JSON.stringify(json.geometry),
            properties: JSON.stringify(json.properties)
          },
          type: 'post',
          success: function (data) {
            entity._attribute.attr.id = data;
          }
        });
      }
    }

    // var json = this.drawControl.toGeoJSON(entity);
    // sendAjax({
    //   url: '',
    //   data: {
    //     id: json.properties.attr.id,
    //     name: json.properties.attr.name,
    //     remark: json.properties.attr.remark,
    //     type: json.properties.type,
    //     coordinates: JSON.stringify(json.geometry),
    //     properties: JSON.stringify(json.properties)
    //   },
    //   type: 'post',
    //   success: function (data) {
    //     entity._attribute.attr.id = data;
    //   }
    // });

  },
  /*对svg进行编辑并处理*/
  // 读取svg代码
  readFile(filePath) {
    // 创建一个新的xhr对象
    let xhr = null
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest()
    } else {
      xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }
    const okStatus = document.location.protocol === 'file' ? 0 : 200
    xhr.open('GET', filePath, false)
    xhr.overrideMimeType('image/svg+xml')
    xhr.send(null)
    return xhr.status === okStatus ? xhr.responseText : null
  },
  //计算svg偏移量 宽 高，中心坐标
  getCoordinateOffset(width, height, pos) {
    //暂定1px=>0.0002度
    const ratio = 0.00001;
    return {
      w: width * ratio,
      h: height * ratio * Math.cos((pos.latitude * Math.PI) / 180),
    };
  },
  //svg贴图加载 图片和坐标
  createRectangle(svgStr, pos) {
    let that=this;
    return new Promise(function (resolve) {
      const textImage = new Image();
      textImage.src =
        "data:image/svg+xml;base64," +
        window.btoa(unescape(encodeURIComponent(svgStr)));

      textImage.onload = function () {
        let imgRange =that.getCoordinateOffset(
          textImage.width,
          textImage.height,
          pos
        );
        let wOffset = imgRange.w / 2;
        let hOffset = imgRange.h / 2;
        that.datasource.entities.add({
          rectangle: {
            material: this.src,
            granularity: Redslib.Math.PI_OVER_FOUR,
            coordinates: Redslib.Rectangle.fromDegrees(
              +pos.longitude - wOffset,
              +pos.latitude - hOffset,
              +pos.longitude + wOffset,
              +pos.latitude + hOffset
            ),
          },
        });
      };
      resolve();
    });
  }

}));